﻿using Shop.Collect;
using Shop.Model.DB;
using Shop.Model.GoodsSku;
using Shop.RemoteModel;
using Shop.RemoteModel.CouponGoods.Model;
using Shop.Service.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;

namespace Shop.Service.lmpl
{
    internal class CouponGoodsService : ICouponGoodsService
    {
        private readonly ICouponGoodsCollect _Service;
        private readonly IGoodsSkuCollect _Sku;
        private readonly ICouponCollect _Coupon;
        private readonly IGoodsSkuStateCollect _SkuState;

        public CouponGoodsService (ICouponGoodsCollect service,
            IGoodsSkuCollect sku,
            ICouponCollect coupon,
            IGoodsSkuStateCollect skuState)
        {
            this._Service = service;
            this._Sku = sku;
            this._Coupon = coupon;
            this._SkuState = skuState;
        }

        public CouponSkuDatum[] Adds (long couponId, CoupGoods[] goods)
        {
            this._Coupon.CheckStatus(couponId, new CouponStatus[]
            {
                CouponStatus.起草,
                CouponStatus.停用
            });
            DBShopCouponGoods[] list = this._Service.Adds(couponId, goods);
            if (list.IsNull())
            {
                return Array.Empty<CouponSkuDatum>();
            }
            return this._Format(list);
        }
        private CouponSkuDatum[] _Format (DBShopCouponGoods[] list)
        {
            long[] skuId = list.ConvertAll(c => c.SkuId);
            SkuDatum[] skus = this._Sku.GetSkuDatums(skuId);
            CouponSkuDatum[] dtos = skus.ConvertMap<SkuDatum, CouponSkuDatum>();
            long[] noEnable = this._SkuState.GetNoEnable(skuId);
            dtos.ForEach(c =>
            {
                c.Id = list.Find(a => a.SkuId == c.SkuId, a => a.Id);
                c.SkuIsEnable = !noEnable.Contains(c.SkuId);
            });
            return dtos;
        }

        public void Delete (long id)
        {
            DBShopCouponGoods sour = this._Service.Get(id);
            this._Coupon.CheckStatus(sour.CouponId, new CouponStatus[]
            {
                    CouponStatus.起草,
                    CouponStatus.停用
             });
            this._Service.Delete(sour);
        }

        public void Delete (long couponId, long[] ids)
        {
            this._Coupon.CheckStatus(couponId, new CouponStatus[]
            {
                    CouponStatus.起草,
                    CouponStatus.停用
             });
            this._Service.Delete(ids);
        }

        public CouponSkuDatum[] GetSkus (long couponId)
        {
            DBShopCouponGoods[] list = this._Service.Gets(couponId);
            if (list.IsNull())
            {
                return Array.Empty<CouponSkuDatum>();
            }
            return this._Format(list);
        }

    }
}
